#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：python_learning 
@File ：frontend.py
@IDE  ：PyCharm 
@Author ：李涵彬
@Date ：2025/2/14 上午9:30 
"""

import sys
import time

from PyQt5.QtCore import pyqtSignal, QThread
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QTextEdit, QVBoxLayout, QWidget


class DataProcessorThread(QThread):
	data_received = pyqtSignal(str)

	def __init__(self, data_queue):
		super().__init__()
		self.data_queue = data_queue

	def run(self):
		while True:
			if not self.data_queue.empty():
				data = self.data_queue.get()
				self.data_received.emit(f"Received data: {data}")
			time.sleep(0.1)


class MainWindow(QMainWindow):
	def __init__(self, data_queue, task_queue):
		super().__init__()
		self.data_queue = data_queue
		self.task_queue = task_queue
		self.log = QTextEdit()
		self.setCentralWidget(self.log)
		self.init_ui()
		self.data_thread = DataProcessorThread(data_queue)
		self.data_thread.data_received.connect(self.update_log)
		self.data_thread.start()

	def init_ui(self):
		self.setWindowTitle("Automation System")
		self.setGeometry(100, 100, 400, 300)
		layout = QVBoxLayout()
		self.log.setReadOnly(True)
		button_db = QPushButton("Update Database")
		button_tcp = QPushButton("Send TCP Message")
		button_clear = QPushButton("Clear Log")
		button_db.clicked.connect(self.on_update_db)
		button_tcp.clicked.connect(self.on_send_tcp)
		button_clear.clicked.connect(self.on_clear_log)
		layout.addWidget(button_db)
		layout.addWidget(button_tcp)
		layout.addWidget(button_clear)
		layout.addWidget(self.log)
		container = QWidget()
		container.setLayout(layout)
		self.setCentralWidget(container)

	def on_update_db(self):
		self.task_queue.put({"type": "update_db", "key": 1, "value": f"Value {time.time()}"})

	def on_send_tcp(self):
		self.task_queue.put({"type": "send_tcp", "message": f"Hello at {time.time()}"})

	def on_clear_log(self):
		self.log.clear()

	def update_log(self, message):
		self.log.append(message)
		# Limit log history (optional)
		if self.log.document().blockCount() > 100:
			cursor = self.log.textCursor()
			cursor.movePosition(cursor.Start)
			cursor.movePosition(cursor.Down, cursor.KeepAnchor, 1)
			cursor.removeSelectedText()


def start_frontend(data_queue, task_queue):
	app = QApplication(sys.argv)
	window = MainWindow(data_queue, task_queue)
	window.show()
	sys.exit(app.exec_())
